package org.makcro.sms.services.chat.web.client.mvc;

import org.makcro.sms.services.chat.web.client.AppEvents;
import org.makcro.sms.services.chat.web.client.Constants;
import org.makcro.sms.services.chat.web.client.mvc.view.MainView;
import org.makcro.sms.services.chat.web.client.services.message.MessageServiceAsync;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;

public class MainController extends Controller {

	private MainView mainView;
	private MessageServiceAsync messageServiceAsync;
	private Timer timer;
	
	public MainController() {
		registerEventTypes(AppEvents.LoginSuccessful);
		registerEventTypes(AppEvents.LOGOUT_REQUESTED);
	}

	@Override
	protected void initialize() {
		super.initialize();
		messageServiceAsync = Registry.get(Constants.Services.MessageService);
		mainView = new MainView(this);
	}

	@Override
	public void handleEvent(AppEvent event) {
		EventType type = event.getType();
		if(type == AppEvents.LoginSuccessful){
			onLoginSuccessful(event);
		}
		else if(type == AppEvents.LOGOUT_REQUESTED){
			onPerformLogout();
		}
	}

	private void onPerformLogout() {
		Window.Location.reload();
		
	}

	private void onLoginSuccessful(AppEvent event) {
		forwardToView(mainView, event);
		initTimer();
		
	}

	private void initTimer() {
		timer = new Timer() {
			
			@Override
			public void run() {
				
				
			}
		};
		timer.schedule(5000);
	}
	
}
